package rabbitMQ.work;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

public class Producer {
    public static void main(String[] args) throws IOException, TimeoutException {
        //创建连接工厂
        ConnectionFactory factory = new ConnectionFactory();

        //设置参数
        factory.setHost("124.223.31.81");
        factory.setPort(5672);
        factory.setVirtualHost("bite");
        factory.setUsername("study");
        factory.setPassword("study");

        //创建连接Connection
        Connection connection = factory.newConnection();

        Channel channel = connection.createChannel();

        /*
         queueDeclare(String queue, boolean durable, boolean exclusive, boolean autoDelete, Map<String, Object> arguments)
         1.queue: 队列名称
         2.durable: 是否持久化.true-设置队列为持久化, 待久化的队列会存盘,服务器重启之后, 消息不
        丢失。
         3.exclusive:
           * 是否独占, 只能有⼀个消费者监听队列
           * 当Connection关闭时, 是否删除队列
         4.autoDelete: 是否⾃动删除, 当没有Consumer时, ⾃动删除掉
         5.arguments: ⼀些参数
         */
        //如果没有⼀个hello_world 这样的⼀个队列, 会⾃动创建, 如果有, 则不创建
        channel.queueDeclare("workQueue", true, false, false, null);

        //6. 通过channel发送消息到队列中
        /*
            basicPublish(String exchange, String routingKey, AMQP.BasicProperties props, byte[] body)
            1.exchange: 交换机名称, 简单模式下, 交换机会使⽤默认的""
            2.routingKey: 路由名称, routingKey = 队列名称
            3.props: 配置信息
            4.body: 发送消息的数据
         */
        for (int i = 0; i < 9; i++) {
            String msg = "Hello rabbitMQ" + i;
            channel.basicPublish("", "workQueue", null, msg.getBytes());
        }

        System.out.println("发送成功");

        //释放资源
        channel.close();
        connection.close();

    }
}

